package dealstandhttp

import (
	"context"
	"core/db"
	"core/server/baseserver"
	"encoding/json"
	"iotall/iotcore/api/proxyup"
	"iotall/iotcore/entity"
	"iotall/iotdeal/deal/basedeal"
	"iotall/iotdeal/dealconfig"
)

type Deal struct {
	basedeal.HttpDeal
}

func (p *Deal) Start() {
	p.HttpDeal.ChildDeal = p.ChildDeal
	p.HttpDeal.Start()

}

func (p *Deal) ChildDeal(ctx context.Context, in *proxyup.UpReq) (*proxyup.UpResp, error) {

	var r = &proxyup.UpResp{
		Ok:   true,
		Msg:  "",
		Data: nil,
		P1:   "",
		P2:   "",
		P3:   "",
		P4:   "",
	}
	//P1 URL  P2 METHOD
	var result = entity.StdResult{
		Code: 0,
		Msg:  "成功",
		Data: "",
	}
	resultData, err := json.Marshal(result)
	r.Data = resultData

	if err != nil {
		return nil, err
	}
	if "GET" == in.P2 {
		return r, nil
	}

	var mpk = &entity.StdPkg{}
	err = json.Unmarshal(in.Data, mpk)
	if err != nil {

		result.Code = 10
		result.Msg = "json格式错误"
		resultData, _ = json.Marshal(result)
		r.Data = resultData
		return r, nil
	}
	mpk.Id = in.ReqId
	mpk.CommPortId = in.CommPortId
	mpk.CommDealId = dealconfig.Config.Id
	mpk.CommProxyId = in.CommProxyId
	mpk.ClientId = in.RemoteAddr
	mpk.PhysicalState = ""

	r.Sid = mpk.Sid
	r.Msg = mpk.GetMemo()

	basedeal.PushStdPkg(mpk)
	if r.Ok && len(r.Data) > 0 {
		r.DownMsg = "确认"
	}
	
	return r, nil
}
func init() {
	var cp = &entity.CommPort{Id: 298212856338460672}
	var tx = db.DbMaster.Model(cp).Find(cp)
	if tx.Error == nil {
		var deal = &Deal{
			basedeal.HttpDeal{
				CommPort:   cp,
				BaseServer: baseserver.BaseServer{Interval: 5000, Name: cp.Name + "处理程序"},
			},
		}
		basedeal.AddDeal(deal)

	}
}
